package com.quan.commons.utils;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;


/**
 * 支持加密配置文件插件
 * 
 * @作者：杨浩泉
 * @日期：2016年10月4日
 */
public class EncryptPropertyConfigurer extends PropertyPlaceholderConfigurer {

	public static final Logger logger = LoggerFactory.getLogger(EncryptPropertyConfigurer.class);

	private static Map<String, String> propertyMap;
	
	private String[] propertyNames = {
			"default.jdbc.password", "slave.jdbc.password", "generator.jdbc.password", "master.redis.password"
		};

	/**
	 * 解密指定propertyName的加密属性值
	 * @param propertyName
	 * @param propertyValue
	 * @return
	 */
	@Override
	protected String convertProperty(String propertyName, String propertyValue) {
		for (String p : propertyNames) {
			if (p.equalsIgnoreCase(propertyName)) {
				return AESUtil.aesDecode(propertyValue);
			}
		}
		return super.convertProperty(propertyName, propertyValue);
	}
	
	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
		super.processProperties(beanFactoryToProcess, props);
		propertyMap = new HashMap<String, String>();
		for (Object key : props.keySet()) {
			String keyStr = key.toString();
			String value = props.getProperty(keyStr);
			propertyMap.put(keyStr, value);
		}
	}

	public static String getValue(String name) {
		String value = propertyMap.get(name);
		if (StringUtils.isBlank(value)) {
			return "";
		} else {
			return value;
		}
	}
	
	/**
	 * 根据key取得value
	 * @param key 键值
	 * @param args value中参数序列，参数:{0},{1}...,{n}
	 * @return
	 */
	public static String getValue(String key, Object... args) {
		String temp = getValue(key);
		return MessageFormat.format(temp, args);
	}
	
	/**
	 * 获取所有资源的Map表示
	 * @return 资源Map
	 */
	public static Map<String, String> getMap() {
		return propertyMap;
	}
	
	public static void main(String[] args) {
		Map<String, String> map = EncryptPropertyConfigurer.getMap();
		System.out.println(map);
	}

}
